﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraBars;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using ProgramMain.Database;

namespace ProgramMain.Framework
{
    public enum PresentFormType
    {
        InVertexes,
        InCableBoxes,
        InEquipment,
        InCableTunnels,
        InCables
    }

    public partial class BaseGridListCtl : ProgramMain.Framework.BaseListViewCtl
    {
        public BaseGridListCtl()
        {
            InitializeComponent();

            this.gridView.PopupMenuShowing += new DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventHandler(this.gridView1_ShowGridMenu);
            this.gridView.DoubleClick += new System.EventHandler(this.gridView1_DoubleClick);
        }

        protected override void OnCreateControl()
        {
            base.OnCreateControl();

            if (this.ParentForm != null)
                this.ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);

            RestoreGridLayout(gridControl, GetType().FullName);
        }

        void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            StoreGridLayout(gridControl, GetType().FullName);
        }

        protected void StoreGridLayout(GridControl gridControl, string layoutID)
        {
            try
            {
                MemoryStream stream = new MemoryStream();

                DevExpress.Utils.OptionsLayoutGrid options = new OptionsLayoutGrid();
                options.StoreVisualOptions = true;
                options.StoreDataSettings = true;
                options.StoreAllOptions = true;
                options.StoreAppearance = true;

                gridControl.MainView.SaveLayoutToStream(stream, options);

                stream.Seek(0, SeekOrigin.Begin);
                StreamReader sr = new StreamReader(stream);

                GlobalData.StoreGridLayoutHistory(layoutID, sr.ReadToEnd());
            }
            catch (Exception ex)
            {
                //do nothing
                System.Diagnostics.Trace.WriteLine(ex.Message);
            }
        }

        protected void RestoreGridLayout(GridControl gridControl, string layoutID)
        {
            if (layoutID == "ProgramMain.OpticNet.FibreList")
                return;
            if (layoutID != null && layoutID.Length > 0)
                try
                {
                    DevExpress.Utils.OptionsLayoutGrid options = new OptionsLayoutGrid();
                    options.StoreVisualOptions = true;
                    options.StoreDataSettings = true;
                    options.StoreAllOptions = true;
                    options.StoreAppearance = true;

                    MemoryStream ms = new MemoryStream();
                    StreamWriter sw = new StreamWriter(ms);

                    sw.Write(GlobalData.ReadGridLayoutHistory(layoutID));
                    sw.Flush();

                    ms.Seek(0, SeekOrigin.Begin);

                    gridControl.MainView.RestoreLayoutFromStream(ms, options);

                    ms.Close();
                    sw.Close();

                    gridControl.Refresh();
                }
                catch (Exception ex)
                {
                    //do nothing
                    System.Diagnostics.Trace.WriteLine(ex.Message);
                }
        }

        override protected void AfterChangeDetailDialog(BaseModalDetailCtl.ShowModeTypes pShowMode, DataRowView RowView)
        {
            if (AutoAcceptChanges && !RefreshAfterChange)
                gridView_FocusedRowChanged(this, new FocusedRowChangedEventArgs(DevExpress.XtraGrid.GridControl.InvalidRowHandle, gridView.FocusedRowHandle));
        }

        protected override void biCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bool bEnabled = this.gridView.OptionsBehavior.Editable;

            this.biCopy.Down = !bEnabled;
            this.gridView.OptionsBehavior.ReadOnly = !bEnabled;
            this.gridView.OptionsBehavior.Editable = !bEnabled;
            this.gridView.OptionsSelection.EnableAppearanceFocusedCell = !bEnabled;
        }

        private PresentFormType _present;
        public PresentFormType Present
        {
            get { return _present; }
            set { _present = value; }
        }


        public virtual void SetActiveRow(int? rowID)
        {
            if (rowID.HasValue)
                try
                {
                    int handle = gridView.LocateByValue("ID", rowID);
                    if (handle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                    {
                        gridView.FocusedRowHandle = handle;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, "Непредвиденная ошибка во время чтения данных!",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
        }

        override protected void RollbackData()
        {
            string tableName = dataSource.DataMember;
            DataTable table = ((DataSet)dataSource.DataSource).Tables[tableName];
            RoolbackDataTable(table);
        }

        private void gridView_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            Nullable<int> CurrentID = new Nullable<int>();
            if (dataSource.Current != null)
            {
                if (e.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                {
                    DataRowView rowView = (DataRowView)gridView.GetRow(e.FocusedRowHandle);
                    if (rowView != null)
                    {
                        DataRow row = (rowView).Row;
                        if (row.Table.Columns.Contains("ID") && !row.IsNull("ID"))
                        {
                            CurrentID = Convert.ToInt32(row["ID"]);
                        }
                    }
                }
            }
            ViewRowID = CurrentID;
        }

        protected void gridView1_ShowGridMenu(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView gridView1 = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Point);
            if (hitInfo.InRow)
            {
                gridView1.FocusedRowHandle = hitInfo.RowHandle;
                //gridView1.FocusedColumn = hitInfo.Column;

                // Update enabled or visible states of popup menu items
                // based on value in focused row and column here.

                this.popupGridMenu.ShowPopup(MousePosition);
            }
        }

        protected void gridView1_DoubleClick(object sender, EventArgs e)
        {
            Action_Edit(sender, EventArgs.Empty);
        }

        protected void treeList1_ShowTreeListMenu(object sender, DevExpress.XtraTreeList.PopupMenuShowingEventArgs e)
        {
            DevExpress.XtraTreeList.TreeList treeList1 = (DevExpress.XtraTreeList.TreeList)sender;
            DevExpress.XtraTreeList.TreeListHitInfo hitInfo = treeList1.CalcHitInfo(e.Point);
            if (hitInfo.Node != null)
            {
                treeList1.FocusedNode = hitInfo.Node;
                //gridView1.FocusedColumn = hitInfo.Column;

                // Update enabled or visible states of popup menu items
                // based on value in focused row and column here.

                this.popupGridMenu.ShowPopup(MousePosition);
            }

        }

        protected void treeList1_ShowGridMenu(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView gridView1 = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Point);
            if (hitInfo.InRow)
            {
                gridView1.FocusedRowHandle = hitInfo.RowHandle;
                //gridView1.FocusedColumn = hitInfo.Column;

                // Update enabled or visible states of popup menu items
                // based on value in focused row and column here.

                this.popupGridMenu.ShowPopup(MousePosition);
            }
        }
    }
}
